<template>
  <a-drawer
      :title="title"
      :maskClosable="true"
      :visible="visible"
      :destroyOnClose="true"
      :width="1000"
      :body-style="{ paddingBottom: '60px' }"
      @close="closeModal"
  >
    <a-form layout="vertical">
      <a-row :gutter="24" :wrap="true">
        <a-col :span="6">
          <a-form-item label="审核流程名" v-bind="validateInfos.name">
            <a-input v-model:value="modelRef.name" placeholder="请输入"/>
          </a-form-item>
        </a-col>
        <a-col :span="6">
          <a-form-item label="审批类型" v-bind="validateInfos.type">
            <a-select v-model:value="modelRef.type" placeholder="请选择">
              <a-select-option
                  v-for="item of typeList"
                  :key="item.key"
                  :value="item.key"
              >{{ item.tab }}
              </a-select-option
              >
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :span="6">
          <a-form-item
              label="流程结束抄送人员"
              v-bind="validateInfos.end_copy_for"
          >
            <a-select
                v-model:value="modelRef.end_copy_for"
                placeholder="请选择"
                mode="multiple"
                show-search
                :filter-option="filterOption"
            >
              <a-select-option
                  v-for="item of userList"
                  :key="item.realname"
                  :value="item.uid"
              >{{ item.realname }}
              </a-select-option
              >
            </a-select>

          </a-form-item>
        </a-col>
        <a-col :span="4">
          <a-form-item label="是否启用" v-bind="validateInfos.status">
            <a-switch
                v-model:checked="modelRef.status"
                :checkedValue="1"
                :unCheckedValue="0"
            />
          </a-form-item>
        </a-col>
        <a-col v-if="addType == 'retreat'" :span="6">
          <a-form-item label="适用退租类型" v-bind="validateInfos.retreat_type">
            <a-select
                v-model:value="modelRef.retreat_type"
                :options="rentingList"
                :max-tag-count="1"
                placeholder="请选择"
                allowClear
                mode="multiple"
            >
            </a-select>
          </a-form-item>
        </a-col>
      </a-row>
      <a-card title="审批节点" size="small">
        <template #extra>
          <a-button type="primary" ghost size="small" @click="addNode()">
            <template #icon>
              <PlusOutlined/>
            </template>
            添加
          </a-button>
        </template>
        <a-card-grid
            style="width: 100%"
            v-for="(nodeKey, index) of nodeList"
            :key="nodeKey"
        >
          <a-row :gutter="24" :wrap="true">
            <a-col :span="5">
              <a-form-item
                  label="节点描述"
                  v-bind="validateInfos[nodeKey + '.title']"
              >
                <a-input
                    v-model:value="modelRef[nodeKey].title"
                    placeholder="请输入"
                />
              </a-form-item>
            </a-col>
            <a-col :span="8">
              <a-form-item
                  label="审核人员"
                  v-bind="validateInfos[nodeKey + '.reviewer']"
              >
                <a-input-group compact>
                  <a-select :style="{width:modelRef[nodeKey].user_type==0?'35%':'100%'}"
                            v-model:value="modelRef[nodeKey].user_type"
                            placeholder="请选择"
                            :options="sendPeopleList"
                            @change="e=>changeUserType(e,nodeKey)"
                  ></a-select>
                  <a-tooltip>
                    <template
                        v-if="modelRef[nodeKey].reviewer?.length>1"
                        #title>
                      {{ getTipUsers(nodeKey) }}
                    </template>

                    <a-select
                        v-if="modelRef[nodeKey].user_type==0"
                        style="width:65%"
                        v-model:value="modelRef[nodeKey].reviewer"
                        placeholder="请选择"
                        :max-tag-count="1"
                        mode="multiple"
                        show-search
                        :filter-option="filterOption"
                    >
                      <a-select-option
                          v-for="item of userList"
                          :key="item.realname"
                          :value="item.uid"
                      >{{ item.realname }}
                      </a-select-option
                      >
                    </a-select>
                  </a-tooltip>
                </a-input-group>

              </a-form-item>
            </a-col>
            <a-col :span="5">
              <a-form-item
                  label="抄送人员"
                  v-bind="validateInfos[nodeKey + '.copyfor']"
              >
                <a-select
                    v-model:value="modelRef[nodeKey].copyfor"
                    placeholder="请选择"
                    mode="multiple"
                    show-search
                    :filter-option="filterOption"
                >
                  <a-select-option
                      v-for="item of userList"
                      :key="item.realname"
                      :value="item.uid"
                  >{{ item.realname }}
                  </a-select-option
                  >
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :span="2">
              <a-form-item v-bind="validateInfos[nodeKey + '.jointly_sign']">
                <template #label>
                  <a-space :size="2">
                    <span>会签</span>
                    <span>
                      <a-tooltip>
                        <template #title
                        >不开启表示任一审核人员同意后就会通过，开启后表示需要所有审核人员同意后才会通过。</template
                        >
                        <QuestionCircleOutlined/>
                      </a-tooltip>
                    </span>
                  </a-space>
                </template>
                <a-switch
                    v-model:checked="modelRef[nodeKey].jointly_sign"
                    :checkedValue="1"
                    :unCheckedValue="0"
                />
              </a-form-item>
            </a-col>
            <a-col :span="2">
              <a-form-item v-bind="validateInfos[nodeKey + '.is_skip']">
                <template #label>
                  <a-space :size="2">
                    <span>跳过</span>
                    <span>
                      <a-tooltip>
                        <template #title
                        >开启跳过后，则此节点会自动同意，并且会显示在「我已审批」中。</template
                        >
                        <QuestionCircleOutlined/>
                      </a-tooltip>
                    </span>
                  </a-space>
                </template>
                <a-switch
                    v-model:checked="modelRef[nodeKey].is_skip"
                    :checkedValue="1"
                    :unCheckedValue="0"
                />
              </a-form-item>
            </a-col>
            <a-col :span="2" v-if="index > 0">
              <a-button @click="delNode(nodeKey, index)" type="link" danger>
                <template #icon>
                  <CloseCircleFilled/>
                </template>
              </a-button>
            </a-col>
          </a-row>
        </a-card-grid>
      </a-card>
      <a-form-item label="选择公司" v-bind="validateInfos.org_branch_id" class="mt-20">
        <a-select
            style="width: 224px"
            mode="multiple"
            v-model:value="modelRef.org_branch_id"
            :options="companyList"
            placeholder="请选择"
            allowClear
        >
        </a-select>
      </a-form-item>
      <a-form-item label="选择项目" v-bind="validateInfos.build" class="mt-20">
        <a-alert
            v-if="disabledTree"
            show-icon
            type="warning"
            message="该审批流程原来绑定的项目/楼宇，您未全部选中，无法修改。"
            class="mb-10"
        />
        <ChooseHousingResources
            checkType="build"
            :allDisabled="disabledTree"
            :defaultChecked="{ buildList: checkedBuildList }"
            @request="$utils.commonRequest"
            @getResult="getResult"
            @error="setCheckedError"
        />
      </a-form-item>
    </a-form>
    <div class="drawer-footer">
      <a-button @click.prevent="closeModal" class="mr-10">关闭</a-button>
      <a-button type="primary" @click.prevent="onSubmit" :loading="submiting">
        保存
      </a-button>
    </div>
  </a-drawer>
</template>

<script>
import {defineComponent, ref, computed, watch, reactive, toRaw} from "vue";
import {Form, message} from "ant-design-vue";
import {ChooseHousingResources} from "bl-common-vue3";
import {
  PlusOutlined,
  CloseCircleFilled,
  QuestionCircleOutlined,
} from "@ant-design/icons-vue";
import store from "../../../../store";
import request from "../../../../common/utils/request";
import utils from "../../../../common/utils/utils";

const useForm = Form.useForm;

export default defineComponent({
  name: "clauseTypeAdd",
  components: {
    ChooseHousingResources,
    PlusOutlined,
    CloseCircleFilled,
    QuestionCircleOutlined,
  },
  props: {
    visible: {
      type: Boolean,
      default: false,
    },
    /**
     {
     "add": "合同新增流程",
     "continue": "续租合同审批",
     "change": "变更合同审批",
     "retreat": "退租合同审批",
     "cancel": "作废合同审批"
     }
     */
    addType: {
      type: String,
      default: "add",
    },
    id: {
      type: [String, Number],
      default: 0,
    },
  },
  setup(props, context) {
    //   标题
    const title = computed(() => {
      return props.id ? "编辑审批流程" : "添加审批流程";
    });

    const typeList = computed(() => store.getters.contractAplTypeList);
    const rentingList = [
      {value: 1 , label:'到期退租'},
      {value: 2 , label:'换房退租'},
      {value: 3 , label:'违约退租'},
      {value: 4 , label:'协商退租'},
    ]

    /**
     * @description:  表单
     */
    const modelRef = reactive({
      name: "",
      type: undefined,
      end_copy_type: undefined,
      end_copy_for: [],
      build: [],
      status: 1,
      org_branch_id:[],
      retreat_type:[],
    });
    const inputRequired = [{required: true, message: "必填项"}];
    const selectRequired = [{required: true, message: "必选项"}];
    const rulesRef = reactive({
      name: inputRequired,
      type: selectRequired,
      build: selectRequired,
      org_branch_id: selectRequired,
    });

    const {resetFields, validate, validateInfos} = useForm(
        modelRef,
        rulesRef
    );

    const closeModal = () => {
      context.emit("cancel")
    };

    const submiting = ref(false);
    const onSubmit = () => {
      if (!disabledTree.value) {
        if (!checkedBuildList.value.length) {
          message.error("请选择关联楼宇~");
          return;
        }
        const buildData = utils.getProjectBuildByBuildList(
            checkedBuildList.value
        );
        modelRef.build = {buildId: buildData.buildId};
      }
      setTimeout(() => {
        validate().then(() => {
          submiting.value = true;

          for (let key in modelRef) {
            if (key.indexOf("node") > -1) {
              modelRef[key].viewer = modelRef[key].user_type != 0 ? [] : modelRef[key].viewer
            }
          }

          let params = {};
          let nodes = [];
          nodeList.value.forEach(key => {
            nodes.push(modelRef[key])
          })

          for (let key in modelRef) {
            if (key.indexOf("node") > -1) {
              // nodes.push(modelRef[key]);
            } else {
              params[key] = modelRef[key];
            }
          }
          params.build = JSON.stringify(params.build);
          params.nodes = JSON.stringify(nodes);
          console.log("params.nodes params.nodes", nodes);
          params.end_copy_for = JSON.stringify(params.end_copy_for);
          params.retreat_type = JSON.stringify(params.retreat_type);
          params.org_branch_id = params.org_branch_id.join()
          const success = (res) => {
            message.success(res.msg || "保存成功");
            context.emit("success");
          };
          let requestMethod = "post";
          let requestUrl = "/process/contract";
          if (props.id) {
            params.id = props.id;
            requestMethod = "put";
          }

          console.log(params, "提交参数")
          request[requestMethod]("/org", requestUrl, params)
              .then((res) => success(res))
              .finally(() => {
                submiting.value = false;
              });
        });
      }, 0);
    };

    // 节点列表
    const nodeList = ref([]);
    const nodeObj = {
      title: "",
      reviewer: [],
      copyfor: [],
      jointly_sign: 0,
      is_skip: 0,
      user_type: 0
    };
    // 添加节点
    let count = 0;
    const addNode = (item) => {
      count++;
      const key = "node_" + count;
      nodeList.value.push(key);
      if (item) {
        modelRef[key] = {
          title: item.title,
          reviewer: item.reviewer,
          copyfor: item.copyfor,
          jointly_sign: item.jointly_sign,
          is_skip: item.is_skip || 0,
          user_type: item.user_type || 0,
        };
      } else {
        modelRef[key] = {
          ...nodeObj,
        };
      }
      rulesRef[`${key}.title`] = inputRequired;
      rulesRef[`${key}.reviewer`] = selectRequired;
    };
    const delNode = (key, index) => {
      nodeList.value.splice(index, 1);
      setTimeout(() => {
        delete modelRef[key];
        console.log(modelRef)
      }, 200)
      delete rulesRef[`${key}.title`];
      delete rulesRef[`${key}.reviewer`];

    };

    // 获取用户列表
    const userList = ref([]);
    const getUserList = () => {
      store.dispatch("GetUserList").then((list) => {
        userList.value = list;
      });
    };

    const disabledTree = ref(false);
    const setCheckedError = (e) => {
      disabledTree.value = true;
    };

    const getResult = (info) => {
      if (disabledTree.value) {
        return;
      }
      const {villageList, buildList} = info;
      let list = [];
      if (villageList.length) {
        for (let village of villageList) {
          list = [...list, ...village.children];
        }
      }
      if (buildList.length) {
        list = [...list, ...buildList];
      }
      checkedBuildList.value = list;
    };

    let detail = {};
    const checkedBuildList = ref([]);
    const getDetail = () => {
      request
          .get("/org", "/process/detail", {
            id: props.id,
          })
          .then((res) => {
            detail = res.data;
            modelRef.name = detail.name;
            modelRef.type = detail.type;
            modelRef.end_copy_for = detail.end_copy_for;
            modelRef.org_branch_id = detail.org_branch_id || []
            modelRef.status = detail.status;
            if (detail.processNode && detail.processNode.length) {
              console.log(detail.processNode)
              detail.processNode.forEach((item) => {
                addNode(item);
              });
            }
            modelRef.build = detail.build;
            modelRef.retreat_type = detail.retreat_type;
            if (detail.build.buildId) {
              checkedBuildList.value = detail.build.buildId.map((id) => ({id}));
            }
          });
    };

    const initNode = () => {
      setTimeout(() => {
        console.log(modelRef)
        for (let key in modelRef) {
          if (key.indexOf("node") > -1) {
            if (!nodeList.value.includes(key)) {

              // delete modelRef[key]
              delete rulesRef[`${key}.title`];
              delete rulesRef[`${key}.reviewer`];
            }
          }
        }
        console.log(modelRef)
      }, 500)
    }

    // 获取用户列表
    const companyList = ref([]);
    const getcompanyList = () => {
      request
          .get("/org", "/company/orgAndBranch", )
          .then((res) => {
            companyList.value = res.list.map((item) => ({
              value: item.id,
              label: item.company,
            }));
          });
    };

    // 初始化
    const init = () => {
      getUserList();
      modelRef.type = props.addType || "add";
      if (props.id) {
        getDetail();
      } else {
        addNode();
      }
      initNode();
      getcompanyList();
      if(props.addType == 'retreat'){
        rulesRef.retreat_type = [{ required: true, message: "必填项"}];
      }else {
        rulesRef.retreat_type = [{ required: false, message: "必填项"}];
      }
    };

    watch(
        () => props.visible,
        (val) => {
          if (val) {
            init();
          } else {
            resetFields();
            checkedBuildList.value = [];
            disabledTree.value = false;
            nodeList.value = [];
            count = 0;
            detail = {};
          }
        }
    );

    const changeUserType = (e, key) => {
      if (e != 0) {
        modelRef[key].reviewer = [""];
      } else {
        modelRef[key].reviewer = [];
      }
    }

    const getTipUsers = (key) => {
      const reviewer = modelRef[key].reviewer
      let str = ''
      for (let i = 0; i < reviewer.length; i++) {
        userList.value.forEach(item => {
          if (item.uid == reviewer[i]) {
            str = str + item.realname + ',';
          }
        })
      }
      if (str.length) {
        str = str.substring(0, str.length - 1)
      }
      return str
    }
    const filterOption = (input, option) => {
      return option.key.toLowerCase().indexOf(input.toLowerCase()) >= 0;
    };

    const sendPeopleList = [
      {label: "指定成员", value: 0},
      {label: "部门负责人", value: 1},
      {label: "上级", value: 2}
    ]
    return {
      title,
      modelRef,
      validateInfos,
      submiting,
      typeList,
      rentingList,
      userList,
      nodeList,
      addNode,
      delNode,
      closeModal,
      onSubmit,
      checkedBuildList,
      getResult,
      setCheckedError,
      disabledTree,
      sendPeopleList,
      changeUserType,
      getTipUsers,
      filterOption,
      getcompanyList,
      companyList,
    };
  },
});
</script>

<style lang="less" scoped></style>
